var user_id;
var voucherImg = []
var heavy_or_empty = ''
var in_or_out = ''
var order_no1 = ''
var order_no2 = ''
var list = [];
var isEdit = false
var order = {}

function bindEmptyContainer (container_no1, container_no2, that) {
  // if (!(voucherImg && voucherImg.length > 0)) {
  //   getApp().alert("请上传图片！");
  //   return
  // }
  if (isEdit) {
    saveEmptyContainer(container_no1, container_no2, that)
    return
  }
  getApp().sp();
  user_id = wx.getStorageSync('user_id');
  var imgs = []
  voucherImg.forEach(function (data) {
    imgs.push({ type: data.type, src: data.src })
  })
  if (!(imgs.length > 0)) {
    imgs = [{}]
  }
  imgs = JSON.stringify(imgs)
  wx.request({
    url: getApp().globalData.apiurl + 'bindEmptyContainer',
    method: 'POST',
    data: {
      "user_id": user_id,
      "container_no1": container_no1,
      "container_no2": container_no2,
      heavy_or_empty: heavy_or_empty,
      in_or_out: in_or_out,
      imgs: imgs
    },
    header: {
      "content-type": "application/x-www-form-urlencoded"
    },
    success: function (res) {

      getApp().hp();
      if (res.data.isSuccess == 1) {
        getApp().alert("绑定成功！")
        setTimeout(function () {
          wx.navigateBack({
            delta: 1
          })
        }, 1500);
      } else {
        getApp().alert(res.data.res);
      }
    }
  })
}

function saveEmptyContainer (container_no1, container_no2, that) {
  // if (!(voucherImg && voucherImg.length > 0)) {
  //   getApp().alert("请上传图片！");
  //   return
  // }
  getApp().sp();
  user_id = wx.getStorageSync('user_id');
  var imgs = []
  voucherImg.forEach(function (data) {
    imgs.push({ type: data.type, src: data.src })
  })
  if (!(imgs.length > 0)) {
    imgs = [{}]
  }
  imgs = JSON.stringify(imgs)
  wx.request({
    url: getApp().globalData.apiurl + 'saveEmptyContainer',
    method: 'POST',
    data: {
      "user_id": user_id,
      id: order.id,
      "container_no1": container_no1,
      "container_no2": container_no2,
      heavy_or_empty: heavy_or_empty,
      in_or_out: in_or_out,
      imgs: imgs
    },
    header: {
      "content-type": "application/x-www-form-urlencoded"
    },
    success: function (res) {

      getApp().hp();
      if (res.data.isSuccess == 1) {
        getApp().alert("绑定成功！")
        setTimeout(function () {
          wx.navigateBack({
            delta: 1
          })
        }, 1500);
      } else {
        getApp().alert(res.data.res);
      }
    }
  })
}


/**
 * TODO(上传媒体文件)
 * @auther zhangQ
 * @date 2018/3/23 13:14
 */
function saveSubOrder (that, orderParam) {
  if (isEdit) {
    orderParam = order.order_no
  }
  if (!orderParam) {
    orderParam = order_no1
  }
  if (!isEdit && !saveSubOrderBefore(that)) {
    wx.showModal({
      title: '提示',
      content: '箱号输入错误！请选择列表中的箱号',
      success: function (res) {
      }
    })
    return
  }
  // if (!(voucherImg && voucherImg.length > 0)) {
  //   getApp().alert("请上传图片！");
  //   return
  // }
  getApp().sp("加载中...");
  var sendData = {
    user_id: wx.getStorageSync('user_id'),
    order_no: orderParam,
    voucher_img: []
  }
  let imgs = []
  voucherImg.forEach(function (data) {
    imgs.push({ type: data.type, src: data.src })
  })
  if (!(imgs.length > 0)) {
    imgs = [{}]
  }
  sendData.voucher_img = JSON.stringify(imgs)
  wx.request({
    url: getApp().globalData.javaurl + '/saveSubOrder',
    method: 'POST',
    data: sendData,
    header: {
      "content-type": "application/x-www-form-urlencoded"
    },
    success: function (res) {
      if (+res.data.isSuccess === 1) {
        if (order_no2) {
          saveSubOrder(that, order_no2)
          order_no2 = ''
          order_no2 = ''
        } else {
          wx.showModal({
            title: '提示',
            content: '上传成功',
            success: function (res) {
              wx.navigateBack({
                delta: 1
              })
            }
          })
        }
      } else {
        wx.showModal({
          title: '提示',
          content: '上传失败',
          success: function (res) {
          }
        })
      }
    },
    complete: function (res) {
      getApp().hp();
    }
  })
}

function saveSubOrderBefore (that) {
  var flag1 = false
  var flag2 = false
  list.forEach(function (item) {
    if (that.data.inputVal1 === item.container_no) {
      flag1 = true
    }
    if (!that.data.inputVal2 || that.data.inputVal2 === item.container_no) {
      flag2 = true
    }
  })
  return (flag1 && flag2)
}

function containerTest (container_no) {
  wx.request({
    url: getApp().globalData.apiurl + 'containerTest',
    method: 'POST',
    data: {
      "container_no": container_no
    },
    header: {
      "content-type": "application/x-www-form-urlencoded",
    },
    success: function (res) {

      return 1;
    }
  })
}


Page({

  /**
   * 页面的初始数据
   */
  data: {
    isEdit: false,
    addresses: ["请选择"],
    addressIndex: 0,
    inputVal1: "",
    inputVal2: "",
    voucher_img: [],
    inputShow1: 0,
    inputShow2: 0
  },
  inputTyping1: function (e) {
    var list2 = [];
    list.forEach(function (data) {
      if (data.container_no && data.container_no.indexOf(e.detail.value) >= 0) {
        list2.push(data);
      }
    })
    this.setData({
      inputVal1: e.detail.value.toUpperCase(),
      inputShow1: 1,
      inputShow2: 0,
      list: list2
    });
    if (e.detail.value == "") {
      this.setData({
        inputShow1: 0,
        inputShow2: 0
      });
    }

  },
  inputTyping2: function (e) {
    var list2 = [];
    list.forEach(function (data) {
      if (data.container_no && data.container_no.indexOf(e.detail.value) >= 0) {
        list2.push(data);
      }
    })
    console.log('list', list2)
    this.setData({
      inputVal2: e.detail.value.toUpperCase(),
      inputShow2: 1,
      inputShow1: 0,
      list: list2
    });
    if (e.detail.value == "") {
      this.setData({
        inputShow1: 0,
        inputShow2: 0
      });
    }
  },
  setVal1: function (e) {
    order_no1 = e.currentTarget.dataset.order_no
    this.setData({
      inputVal1: e.currentTarget.dataset.container_no,
      inputShow1: 0
    })
  },
  setVal2: function (e) {
    order_no2 = e.currentTarget.dataset.order_no
    this.setData({
      inputVal2: e.currentTarget.dataset.container_no,
      inputShow2: 0
    })
  },
  addressChange: function (e) {
    this.setData({
      addressIndex: e.detail.value
    })
  },
  onLoad: function (options) {
    list = [];
    heavy_or_empty = options.heavy_or_empty
    in_or_out = options.in_or_out
    isEdit = !!options.isEdit // 是否编辑模式
    order = {}
    if (isEdit) {
      order = JSON.parse(options.order)
    }
    this.setData({
      "heavy_or_empty": heavy_or_empty,
      "in_or_out": in_or_out,
      isEdit: isEdit
    });
    if (isEdit) {
      var containerNo = order.container_no ? order.container_no : (order.container_no_head + order.container_no_body)
      if (containerNo) {
        this.setData({
          inputVal1: containerNo
        })
      }
    }
    if (options.container_no) {
      this.setData({
        inputVal1: options.container_no
      })
    }
    voucherImg = []
    if (isEdit) {
      if (order.voucher_img) {
        this.addImgs(order.voucher_img)
      } else if (order.imgs) {
        this.addImgs(order.imgs)
      }
    } else if (heavy_or_empty == "1" && in_or_out == "1") {
      this.getAllSubOrderToDriverAndSubOrderList();
    } else if (heavy_or_empty == "0" && in_or_out == "2") {
      this.getLastSubOrder();
    } else if (heavy_or_empty == "0" && in_or_out == "1") {
      this.getRetentionContainerList();
    } else if (heavy_or_empty == "1" && in_or_out == "2") {
      this.getLastEmptyOutContainer();
    }
  },
  addImgs: function (imgs) {
    voucherImg = imgs
    this.setData({
      voucher_img: imgs
    })
  },
  onShow: function () {
    var that = this;
  },
  getAllSubOrderToDriverAndSubOrderList: function () {
    var that = this;
    wx.request({
      url: getApp().globalData.javaurl + '/main/driverOrderDetail/getDriverOrderDetailListByPage',
      method: 'POST',
      data: {
        "state": 1,
        "pageSize":0
      },
      header: {
        "content-type": "application/x-www-form-urlencoded",
        "Authorization": wx.getStorageSync('token')
      },
      success: function (res) {
        list = []
        res.data.data.rows.forEach((item) => {
          list.push({'container_no':item.containerNo})
        })
        console.log(list)
        that.setData({
          "list": list
        });
      }
    });
  },
  getRetentionContainerList: function () {
    var that = this;
    //获取n_station
    let n_station = wx.getStorageSync('n_station');
    console.log(n_station);
    wx.request({
      url: getApp().globalData.javaurl + '/main/station/getRetentionContainerList',
      method: 'POST',
      data: {
        "station": n_station
      },
      header: {
        "content-type": "application/x-www-form-urlencoded",
        "Authorization": wx.getStorageSync('token')
      },
      success: function (res) {
        // var obj = {};
        // obj.container_no = "1270001";
        // list.push(obj);

        // var obj2 = {};
        // obj2.container_no = "1270002";
        // list.push(obj2);
        list = res.data.data.rows;
        that.setData({
          "list": list
        });
      }
    });
  },
  // getRetentionContainerList: function () {
  //   var that = this;
  //   wx.request({
  //     url: getApp().globalData.javaurl + '/main/station/getRetentionContainerList',
  //     method: 'POST',
  //     data: {
  //       "station": "KLR"
  //     },
  //     header: {
  //       "content-type": "application/x-www-form-urlencoded",
  //       "Authorization": wx.getStorageSync('token')
  //     },
  //     success: function (res) {
  //       // var obj = {};
  //       // obj.container_no = "1270001";
  //       // list.push(obj);
  //
  //       // var obj2 = {};
  //       // obj2.container_no = "1270002";
  //       // list.push(obj2);
  //       list = res.data.data.rows;
  //       that.setData({
  //         "list": list
  //       });
  //     }
  //   });
  // },
  getLastSubOrder: function () {
    var that = this;
    user_id = wx.getStorageSync('user_id');
    wx.request({
      url: getApp().globalData.apiurl + 'getLastSubOrder',
      method: 'POST',
      data: {
        "user_id": user_id
      },
      header: {
        "content-type": "application/x-www-form-urlencoded",
      },
      success: function (res) {
        that.setData({
          inputVal1: res.data.data.container_no_head + res.data.data.container_no_body
        });
        console.log(res);
      }
    });
  },
  getLastEmptyOutContainer: function () {
    var that = this;
    user_id = wx.getStorageSync('user_id');
    wx.request({
      url: getApp().globalData.apiurl + 'getLastEmptyOutContainer',
      method: 'POST',
      data: {
        "user_id": user_id
      },
      header: {
        "content-type": "application/x-www-form-urlencoded",
      },
      success: function (res) {
        that.setData({
          inputVal1: res.data.data.container_no
        });
        console.log(res);
      }
    });
  },
  bind: function (e) {
    var that = this;
    var post = e.detail.value;
    var container_no1 = "";
    var container_no2 = "";
    var isSaveSubOrder = (+in_or_out === 1 && +heavy_or_empty === 1)
    if (post.container_no1 == "") {
      getApp().alert("箱号1不能为空！");
      return;
    }
    if (!post.container_no2) {
      post.container_no2 = ""
    }
    post.container_no1 = post.container_no1.replace(/\s/g, '')
    if ((post.container_no1 != "" && !/^\d{7}$/.test(post.container_no1) && !/^[A-Z]{4}\d{7}$/.test(post.container_no1)) || (post.container_no2 != "" && !/^\d{7}$/.test(post.container_no2) && !/^[A-Z]{4}\d{7}$/.test(post.container_no2))) {
      getApp().alert('请输入7位数字或4位字母+7位数字');
      return;
    }
    if (post.container_no1 == post.container_no2) {
      getApp().alert("请不要输入两个相同的箱号！");
      return;
    }
    if (post.container_no1 != "") {
      var res;
      wx.request({
        url: getApp().globalData.apiurl + 'containerTest',
        method: 'POST',
        data: {
          "container_no": post.container_no1
        },
        header: {
          "content-type": "application/x-www-form-urlencoded",
        },
        success: function (ress) {
          res = ress.data;
          console.log(res);
          if (res.isSuccess == 0) {
            getApp().alert(res.res);
            return;
          }
          else if (res.isSuccess == 2) {
            var content = "";
            for (var i = 0; i < res.container_no.length; i++) {
              content = content + "" + res.container_no[i] + "，";
            }
            getApp().alert("您输入的第一个箱号" + post.container_no1 + "有多种可能的字母，分别为：" + content + "请输入完整的11位箱号进行录入！");
            return;
          } else if (res.isSuccess == 1) {
            container_no1 = res.container_no[0];
            //console.log(res);
            that.setData({
              inputVal1: container_no1
            })
            if (post.container_no2 != "") {
              var res;
              wx.request({
                url: getApp().globalData.apiurl + 'containerTest',
                method: 'POST',
                data: {
                  "container_no": post.container_no2
                },
                header: {
                  "content-type": "application/x-www-form-urlencoded",
                },
                success: function (ress) {
                  res = ress.data;
                  if (res.isSuccess == 0) {
                    getApp().alert(res.res);
                    return;
                  } else if (res.isSuccess == 2) {
                    var content = "";
                    for (var i = 0; i < res.container_no.length; i++) {
                      content = content + "" + res.container_no[i] + "，";
                    }
                    getApp().alert("您输入的第二个箱号" + post.container_no1 + "有多种可能的字母，分别为：" + content + "请输入完整的11位箱号进行录入！");
                    return
                  } else if (res.isSuccess == 1) {
                    container_no2 = res.container_no[0];
                    that.setData({
                      inputVal2: container_no2
                    })
                    isSaveSubOrder ? saveSubOrder(that) : bindEmptyContainer(container_no1, container_no2, that);
                  }
                }
              })
            } else {
              isSaveSubOrder ? saveSubOrder(that) : bindEmptyContainer(container_no1, "", that);
            }

          }
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /**
   * TODO(选择媒体文件上传)
   * @auther zhangQ
   * @date 2018/3/24 18:12
   */
  chooseMedia: function () {
    var that = this;
    wx.showActionSheet({
      itemList: ['拍摄照片上传', '拍摄视频上传'],
      success: function (res) {
        if (res.tapIndex == 0) {
          that.choosePhoto();
        } else if (res.tapIndex == 1) {
          that.chooseVideo();
        }
      },
      fail: function (res) {
        console.log(res.errMsg)
      }
    })
  },
  /**
   * TODO(选择图片上传)
   * @auther zhangQ
   * @date 2018/3/24 18:12
   */
  choosePhoto: function () {
    var that = this
    wx.chooseImage({
      count: 6,
      sizeType: ['compressed'],
      // sourceType: ['camera'],
      success: function (res) {
        that.uploadFiles(res.tempFilePaths, 0)
      }
    })
  },
  /**
   * TODO(多张图片上传)
   * @auther zhangQ
   * @date 2018/4/23 11:20
   */
  uploadFiles: function (imgs, index) {
    var that = this
    wx.uploadFile({
      url: getApp().globalData.apiurl + 'uploadFileReturnUrl',
      filePath: imgs[index],
      name: 'file',
      success: function (res) {
        var resData = JSON.parse(res.data);
        var obj = {
          type: 'img',
          src: resData.src
        }
        voucherImg.push(obj)
      },
      complete: function (res) {
        index++
        that.setData({
          voucher_img: voucherImg
        })
        var thatthis = that
        if (index < imgs.length) {
          setTimeout(function () {
            thatthis.uploadFiles(imgs, index)
          }, 200)
        }
      }
    })
  },
  /**
   * TODO(选择视频上传)
   * @auther zhangQ
   * @date 2018/3/24 18:12
   */
  chooseVideo: function () {
    var that = this
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 10,
      camera: 'back',
      success: function (res) {
        wx.uploadFile({
          url: 'https://tp.x-link.cc/DriverApi/' + 'uploadFileReturnUrl',
          filePath: res.tempFilePath,
          name: 'file',
          success: function (res) {
            var resData = JSON.parse(res.data)
            var obj = {
              type: 'video',
              src: resData.src
            }
            voucherImg.push(obj)
          },
          complete: function (res) {
            that.setData({
              voucher_img: voucherImg
            })
          }
        })
      }
    })
  }
})